﻿using Business;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Drawing.Printing;
using Public;
using BarcodeLib;
using System.Runtime.InteropServices;

namespace PFTPickTask
{
    public partial class Form1 : Form
    {
        static string ScanTime = ConfigurationManager.AppSettings["ScanPFTLightInstructionsTime"];//摘果分拣定时器时间间隔
        System.Timers.Timer myTimer;//摘果分拣定时器
        bool _isLight;
        bool isLight
        {
            get { return _isLight; }
            set { _isLight = value; }
        }
        private List<GoodsInfo> list=new List<GoodsInfo>();
        private List<PrintBatchModel> Batchlist = new List<PrintBatchModel>();
        private List<PrintOffShelvesModel> Offlist = new List<PrintOffShelvesModel>();
        public Form1()
        {
            InitializeComponent();
            RYB_PTL_API.RYB_PTL.UserResultAvailable += new RYB_PTL_API.RYB_PTL.UserResultAvailableEventHandler(RYB_PTL_UserResultAvailable);
        }


        #region 事件触发返回值
        /// <summary>
        /// 说明：只要标签有返回值都会自动触发事件绑定的此函数
        /// </summary>
        /// <param name="rs"></param>
        private void RYB_PTL_UserResultAvailable(RYB_PTL_API.RYB_PTL.RtnValueStruct rs)
        {
            try
            {
                string sIp = rs.Ip;
                string sTagId = int.Parse(rs.Tagid).ToString();
                int sValue = int.Parse(rs.Number);
                string sKeyCode = rs.KeyCode;
                string sLocator = rs.Locator;
                string errorMag = "";
                if (!string.IsNullOrEmpty(sIp))
                {
                    if (new BPFTSaleorder().PressElecLabelReaction(sIp, sTagId, sValue, out errorMag))
                    {
                        string sCombineStrToRichTextBox = string.Format("Ip地址:{0},标签ID：{1},货位:{2},特征值:{3},返回数值:{4}", sIp, sTagId, sLocator, sKeyCode, sValue);
                        DisplayRichTextBox(sCombineStrToRichTextBox);
                        isLight = false;
                    }
                    else
                    {
                        DisplayRichTextBox("写入数据失败！原因：" + errorMag);
                    }

                }
                else
                { isLight = true; }

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 说明：显示返回值结果
        /// </summary>
        /// <param name="s"></param>
        private delegate void DelegateDisplay(string s);
        private void DisplayRichTextBox(string s)
        {
            if (InvokeRequired)
            {
                this.Invoke(new DelegateDisplay(DisplayRichTextBox), new object[] { s });
                return;
            }
            else
            {
                richTextBox.AppendText(string.Format("{0}  {1}\r\n", System.DateTime.Now.ToString(), s));
                richTextBox.ScrollToCaret();
                if (richTextBox.Lines.Count() > 1000)
                    richTextBox.Clear();
            }
        }
        #endregion

        #region 摘果分拣
        /// <summary>
        /// 根据IP和ID亮灯
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Light_Click(object sender, EventArgs e)
        {
            try
            {
                int iFrom = Convert.ToInt32(textBox_IDstart.Text);
                int iTo = Convert.ToInt32(textBox_IDend.Text);
                for (int i = iFrom; i <= iTo; i++)
                {
                    isLight = true;
                    RYB_PTL_API.RYB_PTL.RYB_PTL_DspDigit5(textBox_IP.Text, i.ToString().PadLeft(4, '0'), Convert.ToInt32(textBox_number.Text), Convert.ToInt32(textBox_mode.Text), Convert.ToInt32(textBox_color.Text));

                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 根据IP和ID灭灯
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_DisLight_Click(object sender, EventArgs e)
        {
            try
            {
                if (button1.Text == "连接")
                {
                    MessageBox.Show("请先连接控制器，再进行操作。");
                    return;
                }
                int iFrom = Convert.ToInt32(textBox_IDstart.Text);
                int iTo = Convert.ToInt32(textBox_IDend.Text);
                for (int i = iFrom; i <= iTo; i++)
                {
                    bool result = RYB_PTL_API.RYB_PTL.RYB_PTL_CloseDigit5(textBox_IP.Text, i.ToString().PadLeft(4, '0'));
                    DisplayRichTextBox("灭灯结果" + result);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 点亮控制器下所有标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_IPallLight_Click(object sender, EventArgs e)
        {
            try
            {
                if (button1.Text == "连接")
                {
                    MessageBox.Show("请先连接控制器，再进行操作。");
                    return;
                }
                int iFrom = 0;
                int iTo = 100;
                for (int i = iFrom; i <= iTo; i++)
                {
                    isLight = true;
                    RYB_PTL_API.RYB_PTL.RYB_PTL_DspDigit5(textBox_IP.Text, i.ToString().PadLeft(4, '0'), Convert.ToInt32(textBox_number.Text), Convert.ToInt32(textBox_mode.Text), Convert.ToInt32(textBox_color.Text));

                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 熄灭控制器下所有标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonDisIPallLight_Click(object sender, EventArgs e)
        {
            try
            {
                if (button1.Text == "连接")
                {
                    MessageBox.Show("请先连接控制器，再进行操作。");
                    return;
                }
                int iFrom = 0;
                int iTo = 100;
                for (int i = iFrom; i <= iTo; i++)
                {
                    RYB_PTL_API.RYB_PTL.RYB_PTL_CloseDigit5(textBox_IP.Text, i.ToString().PadLeft(4, '0'));
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 点亮所有控制下的所有标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_allLight_Click(object sender, EventArgs e)
        {
            List<PFT_IPListWithIDrange> IPaddressList = new BPFTSaleorder().getIPaddressListWithIDrange();
            if (IPaddressList != null && IPaddressList.Count > 0)
            {
                try
                {
                    foreach (PFT_IPListWithIDrange ip in IPaddressList)
                    {
                        //int iFrom = int.Parse(ip.STARTID);
                        //int iTo = int.Parse(ip.ENDID);
                        //for (int i = iFrom; i <= iTo; i++)
                        //{
                        //    isLight = RYB_PTL_API.RYB_PTL.RYB_PTL_DspDigit5(ip.IPADDRESS.Trim(), i.ToString().PadLeft(4, '0'), 88, 1, 1);
                        //}
                        RYB_PTL_API.RYB_PTL.RYB_PTL_SetMode(ip.IPADDRESS.Trim(), "AAAA", 9);
                    }
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message);
                }
            }
        }

        /// <summary>
        /// 熄灭所有控制下的所有标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_DisallLight_Click(object sender, EventArgs e)
        {
            List<PFT_IPListWithIDrange> IPaddressList = new BPFTSaleorder().getIPaddressListWithIDrange();
            if (IPaddressList != null && IPaddressList.Count > 0)
            {
                try
                {
                    foreach (PFT_IPListWithIDrange ip in IPaddressList)
                    {
                        int iFrom = int.Parse(ip.STARTID);
                        int iTo = int.Parse(ip.ENDID);
                        for (int i = iFrom; i <= iTo; i++)
                        {
                            RYB_PTL_API.RYB_PTL.RYB_PTL_CloseDigit5(ip.IPADDRESS, i.ToString().PadLeft(4, '0'));
                        }
                    }
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message);
                }
            }
        }

        /// <summary>
        /// 显示标签ID
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            RYB_PTL_API.RYB_PTL.RYB_PTL_SetMode(textBox_IP.Text, "AAAA", 9);
        }

        /// <summary>
        /// 自检
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                int iFrom = Convert.ToInt32(textBox_IDstart.Text);
                int iTo = Convert.ToInt32(textBox_IDend.Text);
                for (int i = iFrom; i <= iTo; i++)
                {
                    BLightElecLabel.DisplayElecLabel(textBox_IP.Text, i.ToString().PadLeft(4, '0'), 1, 1);
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 连接控制器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (button1.Text == "连接")
                {
                    //首先连接IP地址,端口号为默认值6020
                    bool isCon = RYB_PTL_API.RYB_PTL.RYB_PTL_Connect(textBox_IP.Text, 6020);
                    if (isCon)
                    {
                        button1.Text = "断开";
                    }
                    else
                    {
                        //查看运行目录下log文件下的日志记录错误信息。
                    }
                }
                else
                {
                    bool isCon = RYB_PTL_API.RYB_PTL.RYB_PTL_Disconnect(textBox_IP.Text);
                    if (isCon)
                    {
                        button1.Text = "连接";
                    }
                    else
                    {
                        //查看运行目录下log文件下的日志记录错误信息。
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 开始分拣
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            //连接所有控制器
            List<PFT_IPListWithIDrange> IPaddressList = new BPFTSaleorder().getIPaddressListWithIDrange();
            if (IPaddressList != null && IPaddressList.Count > 0)
            {
                try
                {
                    foreach (PFT_IPListWithIDrange ip in IPaddressList)
                    {
                        bool isCon = RYB_PTL_API.RYB_PTL.RYB_PTL_Connect(ip.IPADDRESS, 6020);
                    }
                    foreach (PFT_IPListWithIDrange ip in IPaddressList)
                    {
                        RYB_PTL_API.RYB_PTL.RYB_PTL_SetMode(ip.IPADDRESS.Trim(), "AAAA", 9);
                    }
                    foreach (PFT_IPListWithIDrange ip in IPaddressList)
                    {
                        int iFrom = int.Parse(ip.STARTID);
                        int iTo = int.Parse(ip.ENDID);
                        for (int i = iFrom; i <= iTo; i++)
                        {
                            RYB_PTL_API.RYB_PTL.RYB_PTL_CloseDigit5(ip.IPADDRESS, i.ToString().PadLeft(4, '0'));
                        }
                    }

                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message);
                }
            }
            //时间空间开始计时
            DisplayRichTextBox("计时器开始监控......");

            myTimer = new System.Timers.Timer(int.Parse(ScanTime));//定时周期
            myTimer.Elapsed += myTimer_Elapsed;//到秒了做的事件
            myTimer.AutoReset = true; //是否不断重复定时器操作
            myTimer.Enabled = true; //定时器开始用
        }

        void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            List<PFT_LIGHTELECLABELINSTRUCTIONS> info = new BPFTSaleorder().GETLightInstructions();
            if (info != null && info.Count > 0)
            {
                if (new BPFTSaleorder().DELETELightInstructions())
                { DisplayRichTextBox("删除指令成功"); }
                else
                { DisplayRichTextBox("删除指令失败"); }
                foreach (PFT_LIGHTELECLABELINSTRUCTIONS item in info)
                {
                    BLightElecLabel.DisplayElecLabel(item.IPADDRESS, item.LABELID, item.QTY);//点亮电子标签
                    string sCombineStrToRichTextBox = string.Format("点亮标签信息Ip地址:{0},标签ID：{1},数量:{2}", item.IPADDRESS, item.LABELID, item.QTY);
                    DisplayRichTextBox(sCombineStrToRichTextBox);
                }
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            //释放所有控制器
            List<PFT_IPListWithIDrange> IPaddressList = new BPFTSaleorder().getIPaddressListWithIDrange();
            if (IPaddressList != null && IPaddressList.Count > 0)
            {
                try
                {
                    foreach (PFT_IPListWithIDrange ip in IPaddressList)
                    {
                        bool isCon = RYB_PTL_API.RYB_PTL.RYB_PTL_Disconnect(ip.IPADDRESS);//不加IP，释放所有资源
                    }
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message);
                }
            }

            //释放时间控件
            myTimer.Close(); //释放Timer占用的资源
            myTimer.Dispose();
            DisplayRichTextBox("计时器结束监控");
        }

        /// <summary>
        /// 释放巷道，防止死锁影响其他批次分拣
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Release_Roadway_Click(object sender, EventArgs e)
        {
            string roadway = txt_xiangdao.Text.Trim();
            if (string.IsNullOrEmpty(roadway))
            {
                DisplayRichTextBox("请输入巷道号！");
            }
            else
            {
                if (new BPFTSaleorder().Releaseroadway(roadway))
                {
                    DisplayRichTextBox("释放巷道成功！");
                }
                else
                {
                    DisplayRichTextBox("释放巷道失败！");
                }
            }
        }

        #endregion

    }
}
